import 'dart:async';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/ai_poster/ai_poster_index_response_bean.dart';
import 'package:e_reception_flutter/ui/building_index/building_index_diy_page.dart';
import 'package:e_reception_flutter/ui/building_index/diy_list_count_event.dart';
import 'package:e_reception_flutter/ui/building_index/show_set_module_type_bubble_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/widgets/bubble_widget.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_dialog_widget/general_animation_dialog.dart';
import 'package:e_reception_flutter/vg_widgets/vg_mixin/navigator_page_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'building_index_module_page.dart';
import 'building_index_view_model.dart';
import 'change_to_diy_or_module_page_event.dart';
import 'edit_delete_pop_menu_widget.dart';

/// 楼层指示牌首页
class BuildingIndexPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "BuildingIndexPage";
  final int usingCount;

  const BuildingIndexPage({Key key, this.usingCount}) : super(key: key);


  @override
  BuildingIndexPageState createState() => BuildingIndexPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context, int usingCount) {
    return RouterUtils.routeForFutureResult(
      context,
      BuildingIndexPage(
        usingCount: usingCount,
      ),
      routeName: BuildingIndexPage.ROUTER,
    );
  }
}

class BuildingIndexPageState
    extends BasePagerState<AiPosterIndexListItemBean, BuildingIndexPage>
    with
        AutomaticKeepAliveClientMixin,
        VgPlaceHolderStatusMixin,
        NavigatorPageMixin {

  BuildingIndexViewModel _viewModel;
  PageController _pageController;
  ValueNotifier<int> _pageValueNotifier;
  int _diyCount = 2;
  StreamSubscription _changePageStreamSubscription;
  StreamSubscription _showBubbleStreamSubscription;
  StreamSubscription _showMoreOperationStreamSubscription;
  bool _showMoreOperation = false;
  ///获取state
  static BuildingIndexPageState of(BuildContext context) {
    final BuildingIndexPageState result =
    context.findAncestorStateOfType<BuildingIndexPageState>();
    return result;
  }

  bool showBubble = false;
  //水牌模板 00固定模板 01轮换模板
  String _moduleType = "01";
  @override
  void initState() {
    super.initState();
    _viewModel = new BuildingIndexViewModel(this);
    _pageValueNotifier = ValueNotifier(0);
    _pageController = PageController(keepPage: true, initialPage: 0);
    _pageController?.addListener(_setCurrentPage);
    //监听页面跳转
    _changePageStreamSubscription =
        VgEventBus.global.on<ChangeToDiyOrModulePageEvent>()?.listen((event) {
          _pageController.animateToPage(event.page, duration: Duration(milliseconds: 10), curve: Curves.linear);
        });
    //监听diy数量变化
    _showMoreOperationStreamSubscription =
        VgEventBus.global.on<DiyListCountEvent>()?.listen((event) {
          if((event?.count??0) > 0){
            _showMoreOperation = true;
          }else{
            _showMoreOperation = false;
          }
          setState(() { });
        });

    //监听展示设置模板更新类型
    _showBubbleStreamSubscription = VgEventBus.global.on<ShowSetModuleTypeBubbleEvent>()?.listen((event) {
      Future<bool> showBubbleFuture = SharePreferenceUtil.getBool(SP_SAVE_SHOW_SET_MODULE_TYPE_BUBBLE);
      showBubbleFuture.then((value){
        if(((widget?.usingCount??0) == 0) && value??true){
          setState(() {
            showBubble = true;
            SharePreferenceUtil.putBool(SP_SAVE_SHOW_SET_MODULE_TYPE_BUBBLE, false);
          });
        }
      });
    });

    Future<bool> showBubbleFuture = SharePreferenceUtil.getBool(SP_SAVE_SHOW_SET_MODULE_TYPE_BUBBLE);
    showBubbleFuture.then((value) {
      if(((widget?.usingCount??0) == 0) && value??true){
        setState(() {
          showBubble = true;
          SharePreferenceUtil.putBool(SP_SAVE_SHOW_SET_MODULE_TYPE_BUBBLE, false);
        });
      }
    });
  }

  @override
  void dispose() {
    _changePageStreamSubscription?.cancel();
    _showBubbleStreamSubscription?.cancel();
    _pageController?.removeListener(_setCurrentPage);
    _pageController?.dispose();
    _pageValueNotifier?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return LightAnnotatedRegion(
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          resizeToAvoidBottomPadding: false,
          backgroundColor: Colors.white,
          body: Column(
            children: [
              _toTopBarWidget(),
              _toChangeWidget(),
              SizedBox(height: 12,),
              Expanded(child: _toPageWidget()),
            ],
          ),
        )
    );
  }

  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title: "楼层指示牌",
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      rightWidget: _toMoreOperationWidget(),
      rightPadding: 0,
    );
  }

  Widget _toMoreOperationWidget(){
    return Visibility(
      visible: _showMoreOperation,
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTapUp: (details){
          showAnimationDialog(
              context: context,
              transitionType: TransitionType.fade,
              barrierColor: Color(0x00000001),
              transitionDuration: Duration(milliseconds: 100),
              builder: (context) {
                return Material(
                  color: Colors.transparent,
                  child: GestureDetector(
                    behavior: HitTestBehavior.translucent,
                    onTap: () {
                      RouterUtils.pop(context);
                    },
                    child: Container(
                      child: Stack(
                        children: [
                          Positioned(
                              top: details.globalPosition.dy + 15,
                              right: 8,
                              child: Container(
                                decoration: BoxDecoration(
                                    boxShadow: [
                                      BoxShadow(
                                          color: Color(0xff000000).withOpacity(0.1),
                                          offset: Offset(0, 0),
                                          blurRadius: 40
                                      )
                                    ]
                                ),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.end,
                                  children: [
                                    Container(
                                      child: Image.asset("images/sanjiao_white.png",
                                          color: Colors.white,
                                          width: 11, height: 6),
                                      margin: EdgeInsets.only(right: 10),
                                    ),
                                    Container(
                                      // width: 140,
                                      padding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
                                      decoration: BoxDecoration(
                                        color: Colors.white,
                                        borderRadius: BorderRadius.circular(12),
                                      ),
                                      child: Column(
                                        children: [
                                          _toFixModuleWidget(),
                                          _toChangeModuleWidget(),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              ))
                        ],
                      ),
                    ),
                  ),
                );
              }
          );
        },
        onTap: (){
          setState(() {
            showBubble = !showBubble;
          });
        },
        child: Container(
          height: 44,
          width: 50,
          child: Center(
            child: Image.asset(
              "images/icon_more_horizontal.png",
              width: 20,
              height: 20,
            ),
          ),
        ),
      ),
    );
  }

  Widget _toBubbleWidget(){
    return Visibility(
      visible: showBubble,
      child: Positioned(
        top: 0,
        bottom: 0,
        left: 0,
        right: 0,
        child: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: (){
            setState(() {
              showBubble = !showBubble;
            });
          },
          child: Container(
            color: Colors.transparent,
            child: Stack(
              children: [
                Positioned(
                    top: ScreenUtils.getStatusBarH(context) + 44 - 6,
                    right: 15,
                    child: BubbleWidget(
                        140.0,
                        21.0+90,
                        Colors.white,
                        BubbleArrowDirection.top,
                        arrAngle: 85.0,
                        length: 104.0,
                        radius: 12.0,
                        arrHeight: 6.0,
                        strokeWidth: 0.0,
                        child: Column(
                          children: [
                            _toFixModuleWidget(),
                            _toChangeModuleWidget(),
                          ],
                        )
                    )
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }


  ///固定模板
  Widget _toFixModuleWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if("00" == _moduleType){
          return;
        }
        RouterUtils.pop(context);
        _moduleType = "00";
        _viewModel.setModuleType(context, _moduleType);

      },
      child: Container(
        height: 45,
        width: 120,
        padding: EdgeInsets.symmetric(horizontal: 9),
        alignment: Alignment.center,
        child: Row(
          children: [
            Text(
              "固定模板播放",
              style: TextStyle(
                  color: ("00" == _moduleType)?ThemeRepository.getInstance().getPrimaryColor_1890FF():ThemeRepository.getInstance().getCardBgColor_21263C(),
                  fontSize: 14,
                  height: 1.2,
                  decoration: TextDecoration.none
              ),
            ),
            Spacer(),
            Visibility(
              visible: "00" == _moduleType,
              child: Image.asset(
                "images/icon_swoosh_select.png",
                width: 11,
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///轮换模板
  Widget _toChangeModuleWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if("01" == _moduleType){
          return;
        }
        RouterUtils.pop(context);
        _moduleType = "01";
        _viewModel.setModuleType(context, _moduleType);
      },
      child: Container(
        height: 45,
        width: 120,
        padding: EdgeInsets.symmetric(horizontal: 9),
        alignment: Alignment.center,
        child: Row(
          children: [
            Text(
              "每周自动更换",
              style: TextStyle(
                  color: ("01" == _moduleType)?ThemeRepository.getInstance().getPrimaryColor_1890FF():ThemeRepository.getInstance().getCardBgColor_21263C(),
                  fontSize: 14,
                  height: 1.2,
                  decoration: TextDecoration.none
              ),
            ),
            Spacer(),
            Visibility(
              visible: "01" == _moduleType,
              child: Image.asset(
                "images/icon_swoosh_select.png",
                width: 11,
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///切换
  Widget _toChangeWidget(){
    return ValueListenableBuilder(
        valueListenable: _pageValueNotifier,
        builder: (BuildContext context, int page, Widget child){
          return Container(
            width: ScreenUtils.screenW(context) - 30,
            height: 34,
            padding: EdgeInsets.all(3),
            alignment: Alignment.center,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(6),
              color: Color(0xFFF6F7F9),
            ),
            child: Row(
              children: [
                GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: (){
                    _animToPage(0);
                  },
                  child: Container(
                    width: (ScreenUtils.screenW(context) - 30 - 6)/2,
                    height: 28,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: (page == 0)?ThemeRepository.getInstance().getPrimaryColor_1890FF():
                      Colors.transparent,
                      borderRadius: (page == 0)?BorderRadius.circular(4):BorderRadius.circular(0),
                    ),
                    child: Text(
                      "我制作的",
                      style: TextStyle(
                        color: (page == 0)?Colors.white:ThemeRepository.getInstance().getHintGreenColor_5E687C(),
                        fontSize: 12,
                      ),
                    ),
                  ),
                ),
                GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: (){
                    _animToPage(1);
                  },
                  child: Container(
                    width: (ScreenUtils.screenW(context) - 30 - 6)/2,
                    height: 28,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: (page == 1)?ThemeRepository.getInstance().getPrimaryColor_1890FF():
                      Colors.transparent,
                      borderRadius: (page == 1)?BorderRadius.circular(4):BorderRadius.circular(0),
                    ),
                    child: Text(
                      "模板选择",
                      style: TextStyle(
                        color: (page == 1)?Colors.white:ThemeRepository.getInstance().getHintGreenColor_5E687C(),
                        fontSize: 12,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          );
        }
    );


  }

  void _animToPage(int page){
    if(page != 1 && page != 0){
      return;
    }
    _pageController?.animateToPage(page, duration: DEFAULT_ANIM_DURATION, curve: Curves.linear);
  }

  void _setCurrentPage(){
    if(_diyCount < 1){
      return;
    }
    if(_pageController.page >= 0.51){
      _pageValueNotifier.value = 1;
    }else if(_pageController.page <=0.49){
      _pageValueNotifier.value = 0;
    }
    // _pageValueNotifier.value = widget?.pageController?.page?.floor();
  }

  Widget _toPageWidget(){
    if(_diyCount>0){
      return PageView(
        controller: _pageController,
        physics: ClampingScrollPhysics(),
        children: <Widget>[
          BuildingIndexDiyPage(),
          BuildingIndexModulePage(),
        ],
      );
    }else{
      return BuildingIndexModulePage();
    }

  }

  @override
  bool get wantKeepAlive => true;
}
